from catcher.warnings_config import configure_warnings
configure_warnings()

import argparse
from datetime import datetime
from catcher import FuturesArbitrageSystem
from catcher.config import DATA_PATH, FUTURES_CONFIG
import os

def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='期货套利哨兵系统')
    parser.add_argument('--mode', type=str, default='all',
                        choices=['all', 'analysis', 'plot', 'report'],
                        help='运行模式: all=完整运行, analysis=仅分析, plot=仅绘图, report=仅生成报告')
    parser.add_argument('--path', type=str, default=DATA_PATH,
                        help='数据存储路径')
    parser.add_argument('--threshold', type=float, default=2.0,
                        help='预警阈值(标准差的倍数)')
    return parser.parse_args()

def main():
    """主函数"""
    # 解析命令行参数
    args = parse_args()
    
    # 打印启动信息
    print(f"期货套利哨兵系统 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"运行模式: {args.mode}")
    print(f"数据路径: {args.path}")
    print(f"预警阈值: {args.threshold} 倍标准差")
    print("-" * 50)

    try:
        # 初始化系统
        system = FuturesArbitrageSystem(data_path=args.path)
        system.sentinel.std_threshold = args.threshold

        # 根据模式执行相应功能
        if args.mode == 'all':
            # 运行完整分析
            all_price_data = system.calculate_all_price()
            
            # 分析每个品种的Z-score
            print("\n各品种Z-score分析:")
            print("=" * 50)
            
            # 清空之前的信号
            system.sentinel.signals = []
            
            # 分析所有品种并收集信号
            for pair_name, price_data in all_price_data.items():
                signal = system.sentinel.analyze_spread(price_data, pair_name)
                system.sentinel.signals.append(signal)  # 保存信号
                print(f"\n{pair_name} Z-score分析:")
                if 'signals' in signal:
                    for period, data in signal['signals'].items():
                        print(f"{period:>8}: Z得分={data['z_score']:>6.2f}, "
                              f"权重={data['weight']:>4.2f}")
                    print(f"{'加权Z得分':>8}: {signal.get('weighted_z_score', 0):>6.2f}")
                    print(f"{'信号':>8}: {signal.get('signal', '无')}")
                    print(f"{'强度':>8}: {signal.get('strength', '无')}")
                print("-" * 30)
            
            # 生成价差趋势图
            print("\n生成价差趋势图...")
            system.plot_all_price()
            
            # 生成正态分布图
            print("生成正态分布图...")
            system.plot_normal_distribution(all_price_data)
            
            # 生成分析报告
            print("\n生成分析报告...")
            report_path = os.path.join(args.path, "reports")
            os.makedirs(report_path, exist_ok=True)
            report = system.sentinel.generate_report(save_path=report_path)
            print("\n分析报告：")
            print(report)
            
            print("\n图表和报告生成完成")
            
        elif args.mode == 'analysis':
            prices = system.calculate_all_price()
            print(f"分析完成，共处理 {len(prices)} 个期货对")
        elif args.mode == 'plot':
            # 在plot模式下也生成两种图表
            all_price_data = system.calculate_all_price()
            system.plot_all_price()
            system.plot_normal_distribution(all_price_data)
            print("图表生成完成")
        elif args.mode == 'report':
            prices = system.calculate_all_price()
            print("报告生成完成")
        
        print("\n运行成功完成！")
        
    except Exception as e:
        print(f"\n运行出错: {str(e)}")
        raise

if __name__ == "__main__":
    main() 